// import React from 'react'
import { Component } from 'react'
// import HelloWorld from './HelloWorld'
// import DataComp from './DataComp'
import Board from './Board'

import './App.css'

// class App extends React.Component { // class类组件写法
class App extends Component {
    constructor(props) {
        super(props);
        this.handleIndex = this.handleIndex.bind(this)
        this.state = {
            squares: new Array(9).fill(null),
            nextPlayerIsX: true
        }
    }

    handleIndex(index) {
        // console.log(index)
        // this.state.squares[index] = 'X'
        const squaresTemp = this.state.squares.slice()
        if (squaresTemp[index]) {
            return false
        }
        // null => X | O
        if (this.state.nextPlayerIsX) {
            squaresTemp[index] = 'X'
        } else {
            squaresTemp[index] = 'O'
        }

        this.setState({
            squares: squaresTemp, // 修改记录值
            nextPlayerIsX: !this.state.nextPlayerIsX // 切换选手
        })
    }

  render() { // 渲染函数，写HTML
      // 判断输赢 X / O
      const winner = calculateWinner(this.state.squares)
      if (winner && winner.winner) {
          console.log("winner: ", winner)
      }
      let player
      if (!winner) {
          player = <h2>Next Player:{this.state.nextPlayerIsX ? <em>X</em> : <del>O</del>}</h2>
      } else {
          player = <h2>Winner is: {winner.winner} !</h2>
      }

    return (
        <div className="app">
            <h1>井字棋游戏</h1>
            <hr/>
            {/* O / X */}
            {/*<h2>
                { this.state.nextPlayerIsX ? 'X' : 'O' }
                { player }
            </h2>*/}
            { player }

            <Board
                squares={this.state.squares}
                onIndex={this.handleIndex}
                line={winner && winner.line}
            />
        </div>
    );
  }
}

export default App


function calculateWinner(squares) {
    const lines = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6],
    ];
    for (let i = 0; i < lines.length; i++) {
        const [a, b, c] = lines[i];
        if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
            return {
                winner: squares[a], // X | O
                line: lines[i]
            };
        }
    }
    return null;
}



/*
// React 函数式组件的写法
function App() {
  return (
    <div className="App">
      <h1>Hello React</h1>
    </div>
  );
}

export default App;*/
